<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogBindManager.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogBindManager.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    @close="closeDialog"
  >
    <el-form
      ref="bindManagerFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="120"
      style="padding-right: 10px; overflow: auto"
    >
      <el-row style="margin-top: 10px">
        <el-col :span="20">
          <el-form-item label="姓名" prop="personId">
            <el-select v-model="formData.personId" placeholder="请选择" @change="personsChange">
              <el-option
                v-for="item in persons"
                :key="item.personId"
                :label="item.personName"
                :value="item.personId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="20">
          <el-form-item label="身份证编号">
            <el-input v-model="formData.cardNo" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>

        <el-col :span="20">
          <el-form-item label="手机号">
            <el-input v-model="formData.mobile" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="20">
          <el-form-item label="验证码" prop="verificationCode">
            <el-input v-model="formData.verificationCode" placeholder="请输入验证码" />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-button type="success" size="" style="margin-top: 0px" :disabled="disCode" @click="getCode"
            >{{ codeBtn }}
          </el-button>
        </el-col> -->

        <el-col v-if="!existsManager" :span="20">
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" />
          </el-form-item>
        </el-col>
        <el-col v-if="!existsManager" :span="20">
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="formData.confirmPassword" type="password" placeholder="请输入确认密码" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogBindManager.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getVerificationCode } from "@/api/account/project/index";
import { GetWorksiteManager } from "@/api/common/project/index";
import { ManagerExists } from "@/api/common/other/index";
import { BindManager } from "@/api/project/projectInfo/index";
import { ProjectBindManagerForm } from "@/api/project/projectInfo/types";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";

//声明变量
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(450);
const itemSpan = ref(12);
const props = defineProps({
  dialogBindManager: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
    }),
  },
});

const loading = ref(false);
const codeBtn = ref("获取验证码");
const codeCount = ref(60);
const disCode = ref(false);
const existsManager = ref(true);
//通过API获取
const persons = ref();
let codeInterval: NodeJs.Tiemer;

const { dialogBindManager } = toRefs(props);
const emit = defineEmits(["sendClose"]);

const formData = reactive<ProjectBindManagerForm>({});
const bindManagerFormRef = ref();
function passwordBlur(rule: any, value: any, callback: any) {
  if (value === undefined || value === "") {
    callback(new Error("确认密码不能为空"));
  } else {
    if (value != formData.password) {
      callback(new Error("两次密码不一致"));
    } else {
      callback();
    }
  }
}
//表单验证规则
const rules = reactive<FormRules<ProjectBindManagerForm>>({
  personId: [{ required: true, message: "请选择人员", trigger: "change" }],
  confirmPassword: [{ required: true, trigger: "blur", validator: passwordBlur }],
  password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }],
  // verificationCode: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
});

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 500;
    itemSpan.value = 12;
  }
}

function btnToDis() {
  disCode.value = true;
  codeInterval = setInterval(() => {
    if (codeCount.value > 0) {
      codeCount.value--;
      codeBtn.value = `重新获取 (${codeCount.value})`;
    } else {
      disCode.value = false;
      codeCount.value = 60;
      codeBtn.value = "获取验证码";
      clearInterval(codeInterval);
    }
  }, 1000);
}
const getCode = useThrottleFn(async () => {
  if (formData.personId === undefined) {
    ElMessage.error("请选择人员");
    return;
  }
  btnToDis();
  let code = await getVerificationCode(formData.mobile ?? "");
  if (code.success) {
    ElMessage.success("验证码发送成功!");
  } else {
    ElMessage.error(code.msg);
    disCode.value = false;
    codeCount.value = 60;
    codeBtn.value = "获取验证码";
    clearInterval(codeInterval);
  }
}, 3000);

const initForm = () => {
  if (dialogBindManager.value.visible) {
    /**
     * 获取人员列表
     */
    GetWorksiteManager(dialogBindManager.value.id).then((res) => {
      if (res.type === 0) {
        if (res.success === true) {
          persons.value = res.data;
        } else {
          ElMessage.warning(res.msg);
        }
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
};

onMounted(async () => {
  initScreen();
  initForm();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  bindManagerFormRef.value.resetFields();
  bindManagerFormRef.value.clearValidate();
}

const personsChange = function (val: any) {
  formData.personId = persons.value.find((item: any) => item.personId === val).personId;
  formData.cardNo = persons.value.find((item: any) => item.personId === val).cardNumber;
  formData.mobile = persons.value.find((item: any) => item.personId === val).mobile;
  if (formData.cardNo) {
    ManagerExists(formData.cardNo).then((res) => {
      if (res.type === 0) {
        if (res.success === true) {
          existsManager.value = res.data;
        } else {
          ElMessage.warning(res.msg);
        }
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
};
/**
 * 项目表单提交
 */
function handleSubmit() {
  bindManagerFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (dialogBindManager.value.id || dialogBindManager.value.id > 0) {
        formData.projectId = dialogBindManager.value.id;
        BindManager(formData)
          .then((res) => {
            if (res.type === 0) {
              if (res.success === true) {
                ElMessage.success(res.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(res.msg);
              }
            } else {
              ElMessage.warning(res.msg);
            }
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
